package com.genex.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DBbase {
	    public static final String url = "jdbc:mysql://www.0x1000.com/chattyx";  
	    public static final String name = "com.mysql.jdbc.Driver";  
	    public static final String user = "root";  
	    public static final String password = "rootx";  
	  
	    public Connection conn = null;  
	    public Statement    stmt = null;
	    
	    private static DBbase dbDao = new DBbase();
	  
	    public DBbase() {  
	        try {  
	            Class.forName(name);//指定连接类型  
	            conn = DriverManager.getConnection(url, user, password);//获取连接  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	    }  
	  
	    public static DBbase getDbDao(){
	    	return dbDao;
	    }
	    
	    //根据当日，进行访客数据+1统计
	    public void saveViewCounts(){
	    	String dateStr = "";
			Date date = new Date();
			//format的格式可以任意
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				dateStr = sdf.format(date);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	//准备执行语句  
        	 String sql = "insert into day_viewcount(day,count) values('"+dateStr+"',1) ON DUPLICATE KEY UPDATE count=count+1;";
        	 insertEvent(sql);
	    }
	    
	    //根据当日，进行聊天访客数据+1统计
	    public void saveNickCounts(){
	    	String dateStr = "";
			Date date = new Date();
			//format的格式可以任意
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				dateStr = sdf.format(date);
			} catch (Exception e) {
				e.printStackTrace();
			}
        	//准备执行语句  
			String sql = "insert into day_nickcount(day,count) values('"+dateStr+"',1) ON DUPLICATE KEY UPDATE count=count+1;";
       	    insertEvent(sql);
	    }
	   
	    //存储消息
	    public void saveMsg(String nickname,String msg,String clientIP){
	        
	        	//准备执行语句  
	        	 String sql = "insert into msg(nickname,msg,ip,sex,creat_at) values('"+nickname+"','"+msg+"','"+clientIP+"',0,now())";
	        	 insertEvent(sql);
	    }
	   
	    public void insertEvent(String sql){
	        try {
	        
	        	//准备执行语句  
	        	 stmt = conn.createStatement();
	        	 stmt.executeUpdate(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
			   try {
				    stmt.close();
				   } catch (SQLException e) {
				    e.printStackTrace();
				   }
				  }
	    }
	    
}
